﻿/*
 * Copyright (c) 2015 Nathaniel Wallace
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using SalesForceLanguage.Apex.CodeModel;

namespace SalesForceLanguage.Apex.Parser
{
    /// <summary>
    /// Adds methods to the ApexParser class which is auto generated by gppg.
    /// </summary>
    public partial class ApexParser
    {
        #region Fields

        /// <summary>
        /// Holds parser errors that have occured.
        /// </summary>
        private List<LanguageError> _errors = new List<LanguageError>();

        /// <summary>
        /// Holds the non terminal tokens.
        /// </summary>
        private static Tokens[] _nonTermTokens = null;

        /// <summary>
        /// Used to process tokens.
        /// </summary>
        private ApexParserFactory _parserFactory = new ApexParserFactory();

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="scanner">Scanner passed to the parser base class.</param>
        public ApexParser(ApexLexer scanner) 
            : base(scanner)
        {
            _errors = new List<LanguageError>();
            InitNonTermTokens();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Init the non term tokens.
        /// </summary>
        private void InitNonTermTokens()
        {
            if (_nonTermTokens == null)
            {
                _nonTermTokens = new Tokens[nonTerms.Length];
                for (int i = 0; i < nonTerms.Length; i++)
                    if (!nonTerms[i].StartsWith("$"))
                        _nonTermTokens[i] = (Tokens)Enum.Parse(typeof(Tokens), String.Format("grammar_{0}", nonTerms[i]));
            }
        }

        /// <summary>
        /// Parse the apex code.
        /// </summary>
        public ParseResult ParseApex()
        {
            Parse();

            ParseResult result = new ParseResult(
                _parserFactory.Symbols,
                _parserFactory.TypeReferences,
                _errors.ToArray());

            _errors.Clear();
            _parserFactory.Clear();

            return result;
        }

        /// <summary>
        /// Process the reduce.
        /// </summary>
        /// <param name="token">The token that was generated from the reduce.</param>
        /// <param name="values">The values that are being reduced.</param>
        /// <param name="valuesLength">The number of values in the values parameter.</param>
        protected override void ProcessReduce(int token, ApexSyntaxNode[] values, int valuesLength)
        {
            if (token < 0)
            {
                Tokens tokenValue = _nonTermTokens[-token - 1];
                ApexSyntaxNode[] subNodes = (valuesLength == 1 && values[0] == null) ? new ApexSyntaxNode[0] : new ApexSyntaxNode[valuesLength];
                if (subNodes.Length > 0)
                    Array.Copy(values, subNodes, valuesLength);
                CurrentSemanticValue = _parserFactory.Process(tokenValue, CurrentLocationSpan, subNodes);
            }
        }

        /// <summary>
        /// Helper method used to generate a syntax node on an error condition.
        /// </summary>
        protected void Error()
        {
            TextSpan location = new TextSpan(_locationOnError, true);
            foreach (LanguageError err in _errors)
                if (location.CompareTo(err.Location) == 0)
                    YYAbort();

            _errors.Add(new LanguageError(String.Format("Unexpected token: {0}", SymbolToString(_tokenOnError)), location));            
            _errorOccured = true;
            yyerrok();
        }

        #endregion
    }
}
